/**
 * Http访问基础管理类，抽象类
 * Author qiaowy
 * Date 2013-5-23
 * 
 */
package cn.xinliao.net;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.xinliao.model.BaseList;

public abstract class HttpBaseManager {

	/**
	 * 执行网络访问Post操作，返回数据对象
	 * 
	 * @param String
	 *            url 传入网址
	 * @param Object
	 *            sendParam 发送的参数对象，用自己的强类型对象
	 * @param List
	 *            <Object> returnParam 返回的参数对象，用自己的强类型对象
	 */
	public void invokePost(String url, Object sendParam, Object returnParam) {
		// json装箱 ， 发出请求，得到返回的json值
		String responseJson = HttpOperation.postRequestJSONFormat(url,
				jsonBoxing(sendParam));
		// json拆箱
		jsonUnboxing(responseJson, returnParam);
	}

	/**
	 * 执行网络操作访问，返回数据列表
	 * 
	 * @param String
	 *            url
	 * @param Object
	 *            sendParam
	 * @param List
	 *            <Object> returnParamList
	 */
	public void invokePost(String url, Object sendParam,
			List<Object> returnParamList) {
		// json装箱 ， 发出请求，得到返回的json值
		String responseJson = HttpOperation.postRequestJSONFormat(url,
				jsonBoxing(sendParam));
		// json拆箱
		jsonUnboxing(responseJson, returnParamList);
	}

	/**
	 * JSON装箱操作
	 * 
	 * @param Object
	 *            sendObject 传入的参数
	 * @return 返回拼装的JSON字符串
	 */
	public String jsonBoxing(Object sendObject) {
		JSONObject _JsonObject = new JSONObject();
		if (sendObject != null) {
			Field[] _fileds = sendObject.getClass().getDeclaredFields();

			for (Field f : _fileds) {
				f.setAccessible(true);
				Object _value;
				try {
					_value = f.get(sendObject);
					_JsonObject.put(f.getName(), _value);// {"name":"sundy"}
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		return _JsonObject.toString();
	}

	/**
	 * JSON拆箱
	 * 
	 * @param String
	 *            jsonStr 需要拆箱的JSON字符串
	 * @param Object
	 *            returnObject 拆箱完成的对象
	 */
	public Object jsonUnboxing(String jsonStr, Object returnObject) {
		// String reString = "{name:\"todeath\",age:33,isMan:false}" ;
		JSONObject _JsonObject;

		try {
			_JsonObject = new JSONObject(jsonStr);
			if (returnObject != null) {
				Field[] _fileds = returnObject.getClass().getDeclaredFields();

				for (Field f : _fileds) {

					if (_JsonObject.has(f.getName())) {
						f.setAccessible(true);
						f.set(returnObject, _JsonObject.get(f.getName()));
					}

				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returnObject;

	}

	/**
	 * JSON拆箱，返回数据列表
	 * 
	 * @param String
	 *            jsonStr 需要拆箱的JSON字符串
	 * @param BaseList
	 *            <T> baseList 拆箱完成的数据列表
	 */
	@SuppressWarnings("unchecked")
	public <T> List<T> jsonUnboxing(String jsonStr, BaseList<T> baseList) {
		JSONObject _JsonObject;
		List<T> _list = new ArrayList<T>();
		Class<T> _object = null;

		try {
			_object = (Class<T>) Class.forName(baseList.getObjectType());
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			_JsonObject = new JSONObject(jsonStr);
			JSONArray jsonArray = _JsonObject.getJSONArray(_object
					.getSimpleName());
			for (int i = 0; i < jsonArray.length(); i++) {
				_list.add((T) jsonUnboxing(jsonArray.get(i).toString(),
						_object.newInstance()));
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		baseList.setList(_list);
		return baseList.getList();
	}

	/**
	 * JSON装箱操作,List装箱
	 * 
	 * @param BaseList
	 *            <T> sendObjectList 传入的List
	 * @return 返回拼装的JSON字符串
	 */
	@SuppressWarnings("unchecked")
	public <T> String jsonBoxing(BaseList<T> sendObjectList) {
		Class<T> _object = null;
		StringBuilder _stringBuilder = new StringBuilder();
		if (sendObjectList != null) {
			try {
				_object = (Class<T>) Class.forName(sendObjectList
						.getObjectType());
				_stringBuilder.append("{" + _object.getSimpleName() + ":[");
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			for (int i = 0; i < sendObjectList.getCount(); i++) {
				if (i < sendObjectList.getCount() - 1) {
					_stringBuilder.append(jsonBoxing(sendObjectList.getList()
							.get(i)) + ",");
				}

				if (i == sendObjectList.getCount() - 1) {
					_stringBuilder.append(jsonBoxing(sendObjectList.getList()
							.get(i)) + "]}");
				}
			}
		}
		return _stringBuilder.toString();
	}
}
